<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="仓库名称">
                <a-input allow-clear placeholder="请输入仓库名称" v-model="queryParam.name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="手机号">
                <div class="flex">
                  <a-input allow-clear placeholder="请输入手机号" v-model="queryParam.mobile"></a-input>
                  <a-button type="primary" @click="getList()">查询</a-button>
                </div>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>

    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <div></div>

        <a-button type="primary" v-if="userInfo.info.username != 'admin'" @click="visibleCreate = true">添加</a-button>
      </div>

      <a-table
        size="default"
        :columns="columns"
        :data-source="list"
        :row-key="(record) => record.id"
        :pagination="{
          total: this.total,
          pageSize: this.pageSize,
          showSizeChanger: false,
          onChange: this.tablePageChange,
        }"
      >
        <span slot="store_count" slot-scope="text, record">
          <a-button type="link" :disbaled="!parseInt(text)" @click="handleItem('golink', record, 'store')">
            {{ text }}
          </a-button>
        </span>
        <span slot="supplier_count" slot-scope="text, record">
          <a-button type="link" :disbaled="!parseInt(text)" @click="handleItem('golink', record, 'supplier')">
            {{ text }}
          </a-button>
        </span>

        <span slot="address" slot-scope="text, record">
          <a-tooltip>
            <template slot="title"> {{ getAddrName(record) + text }} </template>
            {{ getAddrName(record) + text }}
          </a-tooltip>
        </span>

        <span slot="action" slot-scope="text, record">
          <a-button type="link" size="small" @click="handleItem('login', record)">进入</a-button>
          <a-button
            v-if="userInfo.info.username != 'admin'"
            type="link"
            size="small"
            @click="handleItem('edit', record)"
            >编辑</a-button
          >
          <a-dropdown>
            <a-button type="link" size="small"> 更多 <a-icon type="down" /></a-button>
            <a-menu slot="overlay">
              <a-menu-item v-if="userInfo.info.username != 'admin'">
                <a-button type="link" size="small" @click="onEditPassword(record)">修改密码</a-button>
              </a-menu-item>
              <a-menu-item>
                <a-button type="link" size="small" @click="handleItem('remove', record)">删除</a-button>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>

      <a-modal
        v-model="visibleCreate"
        :title="!formModel.id ? '创建仓库' : '修改仓库'"
        :confirmLoading="confirmLoading"
        @ok="onCreateOk"
        :afterClose="closeModal"
      >
        <a-form-model ref="modelForm" :model="formModel" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
          <a-form-model-item label="账户" has-feedback prop="username">
            <a-input
              v-model="formModel.username"
              :disabled="formModel.username == 'admin'"
              placeholder="请输入账户名"
            />
          </a-form-model-item>
          <a-form-model-item label="是否开启" has-feedback prop="is_enable">
            <a-radio-group v-model="formModel.is_enable" :disabled="formModel.username == 'admin'">
              <a-radio value="1"> 开启 </a-radio>
              <a-radio value="0"> 关闭 </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="密码" v-if="!formModel.id" has-feedback prop="password">
            <a-input v-model="formModel.password" placeholder="请输入密码" />
          </a-form-model-item>
          <a-form-model-item label="手机号" has-feedback prop="mobile">
            <a-input v-model="formModel.mobile" placeholder="请输入手机号" />
          </a-form-model-item>
          <a-form-model-item label="仓库名称" has-feedback prop="name">
            <a-input v-model="formModel.name" placeholder="请输入仓库名称" />
          </a-form-model-item>
          <a-form-model-item label="绑定用户" has-feedback prop="saas_user_id">
            <div style="display: flex">
              <a-input v-model="saas_user_name" disabled />
              <a-button type="primary" @click="visible = true" style="margin-left: 15px">选择</a-button>
            </div>
          </a-form-model-item>
          <!-- <a-form-model-item label="地区" prop="area">
            <Address v-model="formModel.area"></Address>
          </a-form-model-item> -->
          <!-- <a-form-model-item label="区域代理等级">
            <a-select v-model="formModel.area_level" placeholder="请选择区域代理等级">
              <a-select-option value="0"> 默认 </a-select-option>
              <a-select-option value="3"> 省 </a-select-option>
              <a-select-option value="2"> 市 </a-select-option>
              <a-select-option value="1"> 区 </a-select-option>
            </a-select>
          </a-form-model-item> -->
          <a-form-model-item label="备注">
            <a-textarea v-model="formModel.remark" placeholder="请输入备注" :auto-size="{ minRows: 3, maxRows: 5 }" />
          </a-form-model-item>
          <a-form-model-item label="详细地址" has-feedback prop="address">
            <a-input v-model="formModel.address" placeholder="请输入详细地址" />
          </a-form-model-item>
          <a-form-model-item label="坐标" prop="coordinate" help="用逗号分割, 例子:34.819159,113.630390">
            <div class="flex">
              <a-input v-model="formModel.coordinate" @blur="autoSortCoordinate" style="flex: 1; margin-right: 10px" />
              <a-button type="primary" @click="onClickSelectMap"> 选择 </a-button>
            </div>
          </a-form-model-item>
        </a-form-model>
      </a-modal>

      <a-modal title="选择" style="width: 300px" v-model="visible" :destroyOnClose="true" :footer="null">
        <div style="margin-bottom: 10px">
          <a-input-search placeholder="输入昵称搜索" v-model="keyword" allowClear enter-button @search="onSearch" />
        </div>
        <s-table ref="table1" rowKey="id" :columns="userColumns" :data="loadUserData">
          <span slot="baseinfo" slot-scope="text, record">
            <img style="width: 40px; heigth: 40px; border-radius: 3px; margin-right: 5px" :src="record.avatar" />
            <span :length="20" tooltip>{{ record.name }}</span>
          </span>
          <span slot="action" slot-scope="text, record">
            <a-button type="primary" size="small" @click="onSelect(record)"> 选择 </a-button>
          </span>
          <span slot="status" slot-scope="scope">
            <div class="status">
              <span :class="scope.is_disable == 0 ? 'open' : 'close'"></span>
              <span>{{ scope.is_disable == 0 ? '已启用' : '已禁用' }}</span>
            </div>
          </span>
        </s-table>
      </a-modal>
    </a-card>

    <SelectMap
      :oldmarker="formModel.coordinate"
      v-if="mapVisiable"
      :value.sync="mapVisiable"
      @onOk="selectMapOk"
    ></SelectMap>

    <a-modal v-model="visibleEditPassword" title="修改密码" :confirmLoading="confirmLoading" @ok="onEditPasswordOk">
      <a-input placeholder="请输入新密码" v-model="newPassword" />
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { foodExtGoodsSave, foodExtGoodsDel, foodExtGoodsDefault } from '@/api/orderMeal'
import { getAdminListBySaas, editAdminBySaas, editPasswordBySaas } from '@/api/auth'
import { getSelectUserList } from '@/api/user'
import { Address } from '@/components'
import SelectMap from '@/components/SelectMap/SelectMap'
import { address } from '@/api/components/address'
import { STable } from '@/components'
import storage from 'store'
import { generateTokenByFrontAgent } from '@/api/warehouse'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 100,
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '店铺数量',
    dataIndex: 'store_count',
    sorter: (a, b) => a.store_count - b.store_count,
    scopedSlots: {
      customRender: 'store_count',
    },
  },
  {
    title: '供货商数量',
    dataIndex: 'supplier_count',
    sorter: (a, b) => a.supplier_count - b.supplier_count,
    scopedSlots: {
      customRender: 'supplier_count',
    },
  },
  {
    title: '仓库地址',
    dataIndex: 'address',
    scopedSlots: {
      customRender: 'address',
    },
    width: 300,
    ellipsis: true,
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action',
    },
    width: 150,
  },
]

const userColumns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '用户信息',
    scopedSlots: { customRender: 'baseinfo' },
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' },
  },
]
export default {
  components: {
    Address,
    SelectMap,
    STable,
  },
  data() {
    return {
      total: 0,
      pageNo: 1,
      pageSize: 10,
      columns,

      queryParam: {
        name: '',
        mobile: '',
        type: 2,
      },
      list: [],
      selectedRowKeys: [],
      visibleCreate: false,
      visible: false,
      form: {
        name: '',
        desc: '',
        cover_pic: '',
        attr: [],
      },

      rules: {
        username: [{ required: true, message: '请输入账户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
        ],
        name: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
        coordinate: [{ required: true, message: '请输入或选择坐标', trigger: 'blur' }],
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },

      mapVisiable: false,

      formModel: {
        type: 2,
        area: {},
        id: '',
        username: '',
        is_enable: '1',
        password: '',
        mobile: '',
        remark: '',
        name: '',
        expire_time: 0,
        expire_time_always: true,
        saas_user_id: 0,
        address: '',
        coordinate: '',
        area_level: '0',
      },

      addressList: [],

      keyword: '',
      userColumns,
      saas_user_name: '',
      loadUserData: (parameter) => {
        return getSelectUserList({
          ...parameter,
          storeId: storage.get('storeId'),
          type: 'user',
          keyword: this.keyword,
          ...this.queryParam,
        }).then((res) => {
          return res.data
        })
      },

      confirmLoading: false,

      visibleEditPassword: false,
      newPassword: '',

      admin: null,
    }
  },

  watch: {
    visibleCreate(e) {
      if (!e) this.resetForm()
    },
  },

  mounted() {
    this.getList()

    address().then((res) => {
      this.addressList = res.data.list
    })
  },

  computed: {
    getAddrName() {
      return (item) => {
        let str = ''
        if (item.area && item.area.city_id && this.addressList.length) {
          let { city_id, district_id, province_id } = item.area,
            { addressList } = this,
            province = addressList.find((el) => el.id === province_id),
            city = province.cityAll.find((el) => el.id === city_id),
            district = city.districtAll.find((el) => el.id === district_id)

          if (province) {
            str += province.name
          }

          if (city) {
            str += city.name
          }

          if (district) {
            str += district.name || ''
          }
        }
        return str
      }
    },

    userInfo() {
      return this.$store.state.user
    },
  },

  methods: {
    onSelect(item) {
      this.formModel.saas_user_id = item.id
      this.saas_user_name = item.name
      this.visible = false
    },

    onSearch() {
      this.$refs.table1.refresh(true)
    },

    // 获取数据列表
    async getList(pageNo = 1) {
      const hide = this.$message.loading('加载中', 0)
      let { queryParam, pageSize } = this

      const res = await getAdminListBySaas({
        ...queryParam,
        pageSize,
        pageNo,
      })
      if (res.code == 0) {
        this.selectedRowKeys = []
        let { totalCount, data } = res.data
        this.total = totalCount
        this.list = data
      }
      hide()
    },

    // 分页请求
    tablePageChange(e) {
      this.getList(e)
    },

    addList() {
      this.form.attr.push({
        name: '',
        price: '',
        no: '',
        pic: '',
      })
    },

    previewPic(src) {
      this.previewImgSrc = src
      this.showPreviwModal = true
    },

    // 点击单个
    handleItem(type, item, param) {
      switch (type) {
        case 'remove':
          this.remove(item)
          break

        case 'edit':
          this.handleEdit(item)
          break

        case 'login':
          this.login(item)
          break

        case 'golink':
          let { id } = item
          if (param === 'store') {
            this.$router.push({ path: `/warehouse/bindShopList?id=${id}` })
          } else {
            this.$router.push({ path: `/warehouse/bindSupplierList?id=${id}` })
          }
          break
      }
    },

    login(item) {
      generateTokenByFrontAgent({ admin_id: item.id, username: item.username })
        .then((res) => {
          if (res.code == 0) {
            storage.set(ACCESS_TOKEN, res.data.access_token, 7 * 24 * 60 * 60 * 1000)
            this.$store.commit('SET_TOKEN', res.data.access_token)
            storage.set('isSaas', res.data.is_saas)
            storage.set('isSaasStore', false)
            storage.set('storeId', '')
            storage.set('daili', true)
            storage.set('goodsAgent', res.data.admin_name)
            storage.remove('isPlatform')
            storage.remove('isSupplier')
            window.location.href = '/'
          } else {
            this.$message.error('获取token失败')
          }
        })
        .catch((error) => {
          console.log(error)
        })
        .then(() => {})
    },

    handleOk() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let form = JSON.parse(JSON.stringify(this.form))

          if (!form.attr.every((el) => el.name)) {
            return this.$message.error('请完善小料名称～')
          }

          if (!form.attr.every((el) => el.price)) {
            return this.$message.error('请完善小料价格～')
          }

          this.disabled = true
          const hide = this.$message.loading('加载中', 0),
            res = await foodExtGoodsSave(form)

          hide()
          this.disabled = false

          if (res.code == 0) {
            this.$message.success('操作成功！')
            this.visible = false
            this.getList()
            return
          }
          this.$message.error(res.msg)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    remove({ id }) {
      this.$confirm({
        title: '提示?',
        content: '是否删除？',
        onOk: () => {
          foodExtGoodsDel({
            id,
          }).then((res) => {
            if (res.code !== 0) {
              this.$error({
                content: res.msg,
              })
            } else {
              this.$message.success(res.msg)
              this.getList()
            }
          })
        },
        onCancel: () => {},
      })
    },

    foodExtGoodsDefault({ id }) {
      foodExtGoodsDefault({
        id,
      }).then((res) => {
        if (res.code !== 0) {
          this.$error({
            content: res.msg,
          })
        } else {
          this.$message.success(res.msg)
          this.getList()
        }
      })
    },

    resetForm() {
      this.$refs.modelForm.resetFields()
      this.formModel = {
        type: 2,
        area: {},
        id: '',
        username: '',
        is_enable: '1',
        password: '',
        mobile: '',
        remark: '',
        name: '',
        expire_time: 0,
        expire_time_always: true,
        saas_user_id: 0,
        address: '',
        coordinate: '',
      }
    },

    onClickSelectMap: function () {
      this.mapVisiable = true
    },

    selectMapOk(e) {
      this.formModel.coordinate = e
    },

    handleEdit(admin) {
      this.formModel.id = admin.id
      this.formModel.username = admin.username
      this.formModel.is_enable = admin.is_enable
      this.formModel.mobile = admin.mobile
      this.formModel.password = admin.password
      this.formModel.name = admin.name
      this.formModel.saas_user_id = admin.saas_user_id
      this.formModel.expire_time_always = admin.expire_time_always
      this.formModel.expire_time = admin.expire_time
      this.saas_user_name = admin.saas_user_name
      this.formModel.area = admin.area
      this.formModel.address = admin.address
      this.formModel.area_level = admin.area_level
      if (admin.lng && admin.lat) {
        this.formModel.coordinate = `${admin.lat},${admin.lng}`
      } else {
        this.formModel.coordinate = ''
      }

      if (admin.expire_time == '0') {
        this.formModel.expire_time = 0
        this.formModel.expire_time_always = true
      } else {
        this.formModel.expire_time_always = false
        this.formModel.expire_time = moment.unix(this.formModel.expire_time)
      }
      this.visibleCreate = true
    },

    onCreateOk() {
      this.$refs['modelForm'].validate((valid) => {
        if (valid) {
          const formModel = Object.assign({}, this.formModel)
          formModel.expire_time = moment(formModel.expire_time).format('YYYY-MM-DD')
          formModel.coordinate = formModel.coordinate.split(',')
          formModel.lng = formModel.coordinate[1]
          formModel.lat = formModel.coordinate[0]
          delete formModel.coordinate
          this.confirmLoading = true
          editAdminBySaas(formModel)
            .then((res) => {
              if (res.code == 0) {
                this.visibleCreate = false
                this.$message.success(res.msg)
                this.getList()
              } else {
                this.$message.warning(res.msg)
              }
            })
            .catch((error) => {
              console.log(error)
            })
            .then(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    onEditPassword(admin) {
      this.admin = admin
      this.newPassword = ''
      this.visibleEditPassword = true
    },
    onEditPasswordOk() {
      if (this.newPassword == '') {
        this.$message.warning('请输入新密码')
        return
      }
      this.confirmLoading = true
      editPasswordBySaas({
        id: this.admin.id,
        password: this.newPassword,
      })
        .then((res) => {
          if (res.code == 0) {
            this.$message.success(res.msg)
            this.visibleEditPassword = false
          } else {
            this.$message.warning(res.msg)
          }
        })
        .catch((error) => {
          console.log(error)
        })
        .then(() => {
          this.confirmLoading = false
        })
    },
  },
}
</script>

<style lang="less" scoped>
.searchBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 8px 0 18px 0;
  /deep/ .ant-input-affix-wrapper {
    width: 220px;
    margin-right: 20px;
  }
  .select {
    display: flex;
    align-items: center;
    margin-right: 20px;
  }
}

.content {
  display: flex;
  align-items: center;
  height: 48px;
  max-width: 300px;
  overflow: hidden;

  .txt {
    margin-left: 16px;
    flex: 1;
    overflow: hidden;

    * {
      margin: 0;
      font-size: 14px;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }

    h3 {
      color: rgba(0, 0, 0, 0.85);
    }

    p {
      color: rgba(0, 0, 0, 0.45);
    }
  }
}

.flex {
  .inp {
    margin-right: 16px;
  }
}

.table {
  width: 100%;
  margin-top: 10px;
  padding: 10px 12px;

  background: #ffffff;
  border: 1px solid rgba(0, 0, 0, 0.14901960784313725);
  opacity: 1;
  border-radius: 4px;
  .table-body {
    .ant-row {
      min-height: 54px;
      opacity: 1;
      border-radius: 4px 4px 0px 0px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #e8e8e8;
    }
    .self-th {
      background: #fafafa;
    }
  }
  .title {
    .ant-col {
      text-align: center;
      padding: 0 10px;
      font-size: 14px;
      font-family: PingFangSC-Medium;
      line-height: 22px;
      color: rgba(0, 0, 0, 0.85);
    }
  }
}
.list {
  .item {
    background-color: #fff;
    padding: 5px;
    display: flex;
    align-items: center;
    .ant-col {
      text-align: center;
      padding: 0 10px;
    }
  }
}
.tr-row:hover {
  background-color: #e6f7ff;
}

.upload-box {
  width: 50px;
  height: 50px;
  background: rgba(0, 0, 0, 0.05);
  border: 1px dashed rgba(0, 0, 0, 0.14901960784313725);
  opacity: 1;
  border-radius: 4px;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  float: left;
  .upload-content {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }
  .self-com {
    opacity: 0;
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 111;
    /deep/.ant-btn {
      width: 60px;
      height: 60px;
    }
    /deep/.ant-input-group-wrapper {
      width: 60px;
      height: 60px;
      .ant-input-group {
        width: 100%;
        height: 100%;
        span:nth-child(1) {
          display: none;
        }
        span:nth-child(3) {
          width: 100%;
          height: 100%;
          position: absolute;
          left: 0;
          top: 0;
        }
      }
    }
  }
}

.goods_pic_item_box {
  box-shadow: 0 0 5px rgba(170, 170, 170, 0.671);
  border-radius: 3px;
  position: relative;
  margin-right: 10px;
  width: 50px;
  height: 50px;
  background: rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.14901960784313725);
  border-radius: 4px;
  float: left;
  margin: 0 8px 0 0px;
  padding: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  .upload-img-box {
    width: 98%;
    height: 98%;
    position: relative;
    .action-hover {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 11;
      display: none;
      opacity: 0;
      transition: all 0.3s;

      .hover-bg {
        width: 100%;
        height: 100%;
        background-color: #000000;
        opacity: 0.4;
      }
      .hover-body {
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 11;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .action-icons {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 5px;
        .anticon {
          color: #ffffff;
          font-size: 17px;
        }
        .anticon:nth-child(1) {
          margin-right: 10px;
        }
      }
    }
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
  .upload-img-box:hover > .action-hover {
    display: block;
    opacity: 1;
  }
}

.btn {
  text-align: center;
}
</style>
